const { getList, getDetail, newBlog, updateBlog, delBlog } = require("../controller/blog");
const { SuccessModel, ErrorModel } = require("../model/resModel");

/**
 * 统一的登录验证函数
 * @param {*} req
 * @returns
 */

const loginCheck = (req) => {
  if (!req.session.username) {
    return Promise.resolve(new ErrorModel("尚未登录"));
  }
};
/**
 * 博客路由
 * @param {*} req
 * @param {*} res
 * @returns
 */
const handleBlogRouter = (req, res) => {
  const method = req.method; // GET POST

  // 博客列表
  if (method === "GET" && req.path === "/api/blog/list") {
    let author = req.query.author || ""; // 作者
    const isAdmin = req.query.isadmin; // 是否管理页
    const keyword = req.query.keyword || ""; // 标题

    // 是否管理员
    if (isAdmin) {
      const loginCheckResult = loginCheck(req); // 是否登录
      if (loginCheckResult) {
        return loginCheckResult; // 未登录
      }
      author = req.session.username; // 强制查询自己的博客
    }
    const result = getList(author, keyword);
    return result.then((listData) => {
      return new SuccessModel(listData);
    });
  }

  // 详情
  if (method === "GET" && req.path === "/api/blog/detail") {
    const result = getDetail(req.query.id);
    return result.then((data) => {
      return new SuccessModel(data);
    });
  }

  // 新建
  if (method === "POST" && req.path === "/api/blog/new") {
    // 判断是否登录
    const loginCheckResult = loginCheck(req);
    if (loginCheckResult) {
      return loginCheckResult;
    }
    req.body.author = req.session.username; // 获取 redis session 用户信息
    const result = newBlog(req.body);
    return result.then((data) => {
      return new SuccessModel(data);
    });
  }

  // 更新
  if (method === "POST" && req.path === "/api/blog/update") {
    const loginCheckResult = loginCheck(req);
    if (loginCheckResult) {
      return loginCheckResult;
    }
    const result = updateBlog(req.body);
    return result.then((val) => {
      if (val) {
        return new SuccessModel();
      } else {
        return new ErrorModel("更新失败");
      }
    });
  }

  // 删除
  if (method === "POST" && req.path === "/api/blog/del") {
    const loginCheckResult = loginCheck(req);
    if (loginCheckResult) {
      return loginCheckResult;
    }
    const author = req.session.username;
    const result = delBlog(req.query.id, author);
    return result.then((val) => {
      if (val) {
        return new SuccessModel();
      } else {
        return new ErrorModel("删除失败");
      }
    });
  }
};

module.exports = handleBlogRouter;
